package com.ctgu.admin.system.controller;

import com.ctgu.admin.system.domain.Information;
import com.ctgu.admin.system.service.InformationService;
import com.ctgu.admin.system.validator.InformationValid;
import com.ctgu.common.enums.StatusEnum;
import com.ctgu.common.utils.EntityBeanUtil;
import com.ctgu.common.utils.ResultVoUtil;
import com.ctgu.common.utils.StatusUtil;
import com.ctgu.common.vo.ResultVo;
import com.ctgu.component.shiro.ShiroUtil;
import com.ctgu.modules.system.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 该类主要负责站内消息
 */
@Controller
@RequestMapping("/system/information")
public class InformationController {

    @Autowired
    private InformationService informationService;

//    @Autowired
//    private UserService userService;
    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("system:information:index")
    public String index(Model model, Information information) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("title", match -> match.contains());

        // 获取数据列表
        Example<Information> example = Example.of(information, matcher);
        Page<Information> list = informationService.getPageList(example);

        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/system/information/index";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("system:information:add")
    public String toAdd() {
        return "/system/information/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("system:information:edit")
    public String toEdit(@PathVariable("id") Information information, Model model) {
        model.addAttribute("information", information);
        return "/system/information/add";
    }

    /**
     * 保存添加/修改的数据
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"system:information:add", "system:information:edit"})
    @ResponseBody
    public ResultVo save(@Validated InformationValid valid, Information information) {
        // 复制保留无需修改的数据
        if (information.getId() != null) {
            Information beInformation = informationService.getById(information.getId());
            EntityBeanUtil.copyProperties(beInformation, information);
        }

        // 保存数据
        informationService.save(information);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("system:information:detail")
    public String toDetail(@PathVariable("id") Information information, Model model) {
        model.addAttribute("information",information);
        return "/system/information/detail";
    }

    @GetMapping("/myInfo")
    public String toMyInfoPage(Model model){
        User user = ShiroUtil.getSubject();
        List<Information> list = informationService.getInformationByUserId(user.getId());
        model.addAttribute("infoList",list);

        // 各种通知消息的数量
        int[] count = new int[4];
        for (Information info : list) {
            String title = info.getTitle();
            if(title.equals("评论通知")){
                count[0]++;
            }else if(title.equals("审核消息")){
                count[1]++;
            }else if(title.equals("投稿通知")){
                count[2]++;
            }else{
                count[3]++;
            }
        }
        model.addAttribute("count",count);

        model.addAttribute("user",user);
        return "/userPage/myInformation";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("system:information:status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (informationService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
    @RequestMapping("/getInfoNumber")
    @ResponseBody
    public Integer getInfoNumber(){
        User user = ShiroUtil.getSubject();
        List<Information> list = informationService.getInformationByUserId(user.getId());


        return list.size();
    }

    @RequestMapping("/getUserInformation")
    @ResponseBody
    public List<Information> getUserInformation() {

        User user = ShiroUtil.getSubject();
//        if(user==null)
//            user = userService.getById(1L);
        List<Information> list = informationService.getInformationByUserId(user.getId());

        return list.subList(Math.max(list.size() - 3, 0),list.size());
    }

    @GetMapping("/read")
    @ResponseBody
    public Map<String,String> readInformationById(Long id){
        int result = informationService.readInformationById(id);
        Map map = new HashMap<String,String>();
        String msg = "";
        if(result != 0){
           msg = "已读成功";
        }else{
            msg = "已读失败";
        }
        map.put("msg",msg);
        return map;
    }

}